<script>
import { computed, defineComponent, inject, reactive, ref, toRaw } from 'vue'
import { favoriteList } from '@Config/server/api'
import DataTable from '@Components/dataTable'
import { createPagination, Messages, uploadParams } from '@Config/config'
import { message, Modal } from 'ant-design-vue'
import MakeForm, { MakeFormState } from '@Components/makeForm'
import ColorBlock from '@Components/colorBlock'
import { useUrl, transform_pre_fn } from '@Hooks/url'
import { useRoute, useRouter } from 'vue-router'
import FolderList from '@Components/folderList'
import { fileType, fileTypeDataStaus } from '@Config/const'
import { cloneDeep, findIndex, uniqueId } from 'lodash'
import { useStore } from 'vuex'
import useBreadcrumb from '@Hooks/breadcrumb'
import { useWin } from '@Hooks/win'
import ReName from '@Page/my/components/rename'
import RelationPath from '@Page/my/components/relationPath'
import * as Antd from 'ant-design-vue'
import { instanceFn } from '@Page/favorites/fn'
import { IconShanChu, IconHuFu, IconXinJian } from '@Assets/fonts/svg'
import Tips from '@Components/tips'

export default defineComponent({
  components: {
    DataTable,
    MakeForm,
    ColorBlock,
    FolderList,
    ReName,
    RelationPath,
  },
  setup(props, context) {
    let store = useStore()
    let router = useRouter()
    let route = useRoute()

    let {
      deleteFavoriteFolder,
      createFavoriteFolder,
      editFavoriteFolder,
    } = instanceFn()
    let form_config = []
    let form_state = reactive({ data: MakeFormState(form_config) })
    //表格数据配置
    let tableData = reactive({
      data: {
        source: [],
        columns: [
          {
            key: 'yyyyMmDd',
            dataIndex: 'yyyyMmDd',
            title: '',
          },
        ],
      },
    })

    //表格loading状态
    let loading = reactive({ search_loading: false })

    let resetHandler = () => {
      form_ref.value.resetState()
      pagination.data.current = 1
      searchData()
    }
    //查询按钮监听
    let searchHandler = () => {
      pagination.data.current = 1
      searchData()
    }

    let { fromStateToQuery, forceFresh } = useUrl({
      fn: async () => {
        loading.search_loading = true
        let _params = {
          ...form_state.data,
          index: pagination.data.current,
          size: pagination.data.pageSize,
        }
        let _result = await favoriteList(_params)
        if (_result.code != 0) {
          Messages.add(message.error('查询失败' + _result.msg))
          pagination.data.pageSize = 0
          pagination.data.current = 1
          pagination.data.total = 0
          tableData.data.source = []
          return
        } else {
          pagination.data.pageSize = _result.data?.size
          pagination.data.current = _result.data?.index
          pagination.data.total = _result.data?.total
          tableData.data.source = _result.data?.records
        }

        loading.search_loading = false
      },
      formState: [],
    })
    //查询数据
    let searchData = async () => {
      fromStateToQuery({ path: route.path })
    }

    //表格分页
    let pagination = reactive({
      data: createPagination(searchData, true, false),
    })

    //分页点击
    // pagination.data.onChange = (pageNumber, pageSize) => {
    //   pagination.data.current = pageNumber
    //   pagination.data.pageSize = pageSize
    //   searchData()
    // }
    //ref dom
    let form_ref = ref(null)
    //新增公告回调函数

    //默认查询
    //searchData()

    let selectHandler = (e) => {
      router.push({
        name: 'FavoritesList',
        query: {
          fid: e.target.id,
        },
      })

      // //searchHandler()
      // form_state.data.id = e.target.id
      // tableData.data.source.map((x) => {
      //   if (x.id == e.target.id) {
      //     x.local_loading = true
      //   }
      // })
      // fromStateToQuery({ path: route.path })
      // addPath({ ...e.target })
    }
    //监听 文件夹、文件是否选中
    let checkBoxHandler = (e) => {
      let _index = findIndex(tableData.data.source, { id: e.target.id })
      tableData.data.source[_index].selected = e.e.target.checked
    }

    /**
     * 选中的单位
     */
    let tables_selected = computed(() => {
      return tableData.data.source.filter((x) => x.selected)
    })

    //基础菜单
    let rmenu = [
      {
        label: '新建备份文件夹',
        action: createFavoriteFolder,
        icon: <IconXinJian />,
      },
    ]

    let batch_menu = reactive({
      data: [
        {
          label: '批量删除',
          action: () => {
            deleteFavoriteFolder(tables_selected.value)
          },
          icon: <IconShanChu />,
          attr: () => {
            return { disabled: tables_selected.value.length == 0, danger: true }
          },
        },
      ],
    })
    let mainMenu = () => {
      return [...rmenu, ...batch_menu.data]
    }

    //注册右上角的菜单
    let rightMenu = inject('rightIconMenu')
    //右上角菜单
    rightMenu.data = rmenu.map((x) => {
      return {
        ui: (
          <a-menu-item>
            <a-button type="link" size="small" onClick={x.action}>
              {x.label}
            </a-button>
          </a-menu-item>
        ),
      }
    })

    //右键菜单
    let rightMenuHandler = (e) => {
      if (!e.rightMenu) {
        e.rightMenu = (
          <Antd.Menu selectedKeys={[]} class="mymenu">
            {rmenu?.map((x) => {
              return (
                <a-menu-item>
                  <a-button type="link" size="small" onClick={x.action}>
                    {x.label}
                  </a-button>
                </a-menu-item>
              )
            })}
            {batch_menu.data?.map((x) => {
              return (
                <a-menu-item>
                  <a-button
                    type="link"
                    size="small"
                    onClick={x.action}
                    {...x.attr()}
                  >
                    {x.label}
                  </a-button>
                </a-menu-item>
              )
            })}

            <Antd.MenuItem>
              <Antd.Button type="link" onClick={forceFresh} size="small">
                刷新
              </Antd.Button>
            </Antd.MenuItem>
          </Antd.Menu>
        )
      }
    }

    //右键文件，弹出菜单选项
    let folder_right_menu_fn = () => {
      return () => {
        return [
          {
            label: '编辑',
            action: editFavoriteFolder,
          },
          {
            label: '删除',
            action: (x) => deleteFavoriteFolder([x]),
          },
        ]
      }
    }

    //选择/取消 全部
    let selectAllHandler = (e) => {
      tableData.data.source.map((x) => {
        x.selected = e.target.checked
      })
    }

    return {
      tableData,
      loading,
      pagination,
      form_config,
      form_state,
      form_ref,
      selectHandler,
      checkBoxHandler,
      selectAllHandler,
      tables_selected,
      rightMenuHandler,
      forceFresh,
      folder_right_menu_fn,
      batch_menu,
      rmenu,
      mainMenu,
    }
  },
  render() {
    return this.loading.search_loading ? (
      <a-spin tip="数据加载中..." />
    ) : (
      <a-row gutter={[20, 20]} onContextmenu={this.rightMenuHandler}>
        <a-col span={24}>
          <Tips
            list={this.tableData.data.source}
            selected={this.tables_selected}
          >
            <a-space>
              {this.mainMenu().map((x) => {
                return (
                  <a-button
                    type="primary"
                    shape="circle"
                    onClick={x.action}
                    title={x.label}
                    {...(x.attr ? x.attr() : null)}
                  >
                    {x.icon}
                  </a-button>
                )
              })}
              <a-checkbox onChange={this.selectAllHandler}>全选</a-checkbox>
            </a-space>
          </Tips>
        </a-col>
        <a-col span={24} class="vh69">
          <FolderList
            list={cloneDeep([...this.tableData.data.source])}
            onSelect={this.selectHandler}
            onCheckBox={this.checkBoxHandler}
            rightMenuFn={this.folder_right_menu_fn()}
            role="common"
          />
          <a-affix {...this.pagination_affix_attr()}>
            <div class="affix">
              <a-pagination {...this.pagination.data} />
            </div>
          </a-affix>
        </a-col>
      </a-row>
    )
  },
})
</script>
